//
//  ReservationC.m
//  WHSport
//
//  Created by 蒋宇 on 15/6/1.
//  Copyright (c) 2015年 jimneylee. All rights reserved.
//

#import "ReservationC.h"
#import "Util.h"
#import "BusinessModel.h"
#import "UserModel.h"
#import "JZ320Library.h"
#import "KWFormViewQuickBuilder.h"
#import "BusinessModel.h"
#import "NSDateAdditions.h"

@interface WeekButton : UIButton
+ (WeekButton *)buttonWithTitle:(NSString *)title;
@end

@implementation WeekButton

+ (WeekButton *)buttonWithTitle:(NSString *)title {
    WeekButton *button = [[self alloc] init];
    button.bounds = CGRectMake(0, 0, 66, 44);
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [button setTitleColor:RGBCOLOR(16, 191, 229) forState:UIControlStateSelected];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    
    return button;
}

@end

@interface ReservationC () <KWFormViewDelegate, KWFormViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *ibHeader;
@property (weak, nonatomic) IBOutlet UIView *ibContent;
@property (weak, nonatomic) IBOutlet UILabel *ibValueLabel;

@property (nonatomic, strong) UIButton *lastSelectedScheduleTimeButton;
@end

@implementation ReservationC {
    NSMutableArray *results;
    
    NSMutableDictionary *_statueList;
    NSArray *_timeList;
    NSArray *_yardList;
    
    NSArray *_formTitles;
    NSMutableArray *_formDatas;
    
    NSMutableArray *yardUnits;
    
    NSString *_selectedYardId;
    NSString *_totalPrice;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    yardUnits = [NSMutableArray array];
    results = [NSMutableArray array];
    
    [self configHeadScroll];
    [self getData];
}

- (void)configHeadScroll {
    
    UIScrollView *scroll = [[UIScrollView alloc] init];
    scroll.size = CGSizeMake(MAIN_SCREEN_SIZE.width,
                             self.ibHeader.height);
    scroll.alwaysBounceHorizontal = YES;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.backgroundColor = [UIColor clearColor];
    
    
    NSArray *dateArray = [self dateArrayByNowDate];
    for (int i=0; i<dateArray.count; i++) {
        NSDictionary *dic = dateArray[i];
        WeekButton *button = [WeekButton buttonWithTitle:
                              [NSString stringWithFormat:@"%@\n%@",
                               dic[@"date"],
                               dic[@"week"]]];
        [button addTarget:self
                   action:@selector(tapScheduleTimeButton:)
         forControlEvents:UIControlEventTouchUpInside];
        button.left = CELL_PADDING_8 + i*(CELL_PADDING_8+button.width);
        button.centerY = scroll.height * .5f;
        [scroll addSubview:button];
        
        if (i == 0) {
            button.selected = YES;
            _lastSelectedScheduleTimeButton = button;
        }
    }
    
    scroll.contentSize = CGSizeMake(CELL_PADDING_8*2 + (CELL_PADDING_8+66)*dateArray.count,
                                                 self.ibHeader.height);
    [self.ibHeader addSubview:scroll];
}

- (void)tapScheduleTimeButton:(UIButton *)btn {
    btn.selected = YES;
    _lastSelectedScheduleTimeButton.selected = NO;
    _lastSelectedScheduleTimeButton = btn;
}

- (NSArray *)dateArrayByNowDate {
    NSMutableArray *result = [NSMutableArray array];
    
    NSDate*nowDate = [NSDate date];
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd"];
    NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"yyyy-mm-dd"];
    NSDate* theDate;
    for (int i = 0; i<7; i++) {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        theDate = [nowDate initWithTimeIntervalSinceNow:oneDay*i];
        NSString *allDate=[dateFormatter stringFromDate :theDate];
        NSString *allDate1=[dateFormatter1 stringFromDate :theDate];
        NSString *date = [Util weekdayStringFromDate:theDate];
        if ([date isEqualToString:@"Sunday"]) {
            date = @"周日";
        }
        NSDictionary *dic = @{@"date":allDate,@"week":date,@"allday":allDate1};
        [result addObject:dic];
    }
    
    return [result copy];
}

- (void)configGrid:(NSArray *)times
            prices:(NSDictionary *)prices
             yards:(NSArray *)yards {
    if (times.count==0 ||
        prices.count== 0 ||
        yards.count == 0) {
        NSLog(@"没有数据！");
        return;
    }
    
//    KWFormViewQuickBuilder *builder = [[KWFormViewQuickBuilder alloc] init];
    
    NSMutableArray *yardNames = [NSMutableArray array];
    yardNames[0] = @"时间";
    
    for (int i=0; i<yards.count; i++) {
        [yardNames addObject:yards[i][@"yardUnitName"]];
    }
//    [builder addRecord:yardNames];
    
    _formTitles = yardNames;
    _formDatas = [NSMutableArray array];
    
    
    for (int i=0; i<times.count; i++) {
//        NSMutableArray *temps = [NSMutableArray array];
        NSMutableArray *result_prices = [NSMutableArray array];
        
        NSString *time = times[i];
        NSArray *venues = prices[time];
//        [temps addObject:time];
        [result_prices addObject:time];
        
//        NSMutableArray *actions = [NSMutableArray array];
//        [actions addObject:noAction];
        
        for (int j=0; j<venues.count; j++) {
//            [temps addObject:[venues[j][@"price"] stringValue]];
            [result_prices addObject:[venues[j][@"price"] stringValue]];
//            [actions addObject:@"tapedButton:indexPath:"];
        }
        
//        [builder addRecord:temps SELNames:actions];
        
        [_formDatas addObject:result_prices];
    }
    
//    [builder setActionTarget:self];
    
    NSMutableArray *widths = [NSMutableArray array];
    for (int i=0; i<yardNames.count; i++) {
        [widths addObject:@(70)];
    }
    
//    KWFormView *formView = [builder startCreatWithWidths:widths
//                                              startPoint:CGPointMake(0, 0)];
    KWFormView *formView = [[KWFormView alloc] init];
    formView.left = 0;
    formView.top = 0;
    formView.dataSource = self;
    formView.delegate = self;
    
    UIScrollView *contentScroll = [[UIScrollView alloc] init];
    contentScroll.size = CGSizeMake(MAIN_SCREEN_SIZE.width, self.ibContent.height);
    [self.ibContent addSubview:contentScroll];
    
    [contentScroll addSubview:formView];
    contentScroll.contentSize = formView.size;
}

- (void)getData {
    NSString *sporth = self.sportHid;
    NSString *sporte = self.sportEid;
    NSString *stime = self.time;
    NSString *sacid = [NSString stringWithFormat:@"%@",
                       [UserModel sharedInstance].currentUser.ID];
    
    [[BusinessModel sharedInstance]
     getReservationWithSporthall:sporth
     scheduledTime:stime
     accountId:sacid
     Sportevent:sporte
     returnData:^(id info) {
         NSArray *timeArray = info[@"timesolt"];
         NSDictionary *priceArray = info[@"statusList"];
         NSArray *yardArray = info[@"yardUnits"];
         
         _timeList = timeArray;
         _yardList = yardArray;
         _statueList = [priceArray mutableCopy];
         
         [self configGrid:timeArray
                   prices:priceArray
                    yards:yardArray];
     }];
}

- (NSInteger)checkIfExist:(NSDictionary *)dic {
    for (int i=0; i<yardUnits.count; i++) {
        NSDictionary *temp = yardUnits[i];
        NSString *timesolt = temp[@"timesolt"];
        NSString *yardNumber = temp[@"yardNumber"];
        
        if ([timesolt isEqualToString:dic[@"timesolt"]] &&
            [yardNumber isEqualToString:dic[@"yardNumber"]]) {
            return i;
        }
    }
    
    return -1;
}

- (IBAction)ibaOrder:(id)sender {
    [[BusinessModel sharedInstance]
     generateTheOrderWithYardId:_selectedYardId
     accountId:[[[UserModel sharedInstance] currentUser] ID]
     status:@"1"
     sportsEventId:self.sportEid
     scheduledTime:[[NSDate date] formatDateWithStyle:@"yyyy-M-d"]
     totalPrice:_totalPrice
     yardUnits:yardUnits
     resultBlcok:^(id info) {
         NSLog(@"info is %@", info);
         
         [self payOrder:info];
     }];
}

- (void)payOrder:(id)info {
    
}

#pragma mark - formView dataSource
- (NSInteger)numberOfRowsInFormView:(KWFormView *)formView
{
    return _formDatas.count + 1;
}

- (NSInteger)formViewColumnsInRow:(KWFormView *)formView
{
    return _formTitles.count;
}

- (NSString *)formView:(KWFormView *)formView
         textForColumn:(NSInteger)column
                 inRow:(NSInteger)row
{
    if (!row) {
        return _formTitles[column];
    }else{
        NSArray *rowData = _formDatas[row-1];

        NSString *content = nil;
        if (column == 0) {
            content = [NSString stringWithFormat:@"%@点", rowData[column]];
        } else {
            content = [NSString stringWithFormat:@"%@元", rowData[column]];
        }
        return content;
    }
}

- (UIColor *)formView:(KWFormView *)formView
        colorOfColumn:(NSInteger)column
                inRow:(NSInteger)row
{
    if (row == 0) {
        return [UIColor clearColor];
    }

    if (column == 0) {
        return DEFAUTLT_BACKGROUND_COLOR;
    }
    
    if (row!=0 && column!=0) {
        NSString *time = _timeList[column];
        NSDictionary *dic = _statueList[time][column-1];
        BOOL statue = [dic[@"status"] boolValue];
        if (!statue) {
            return RGBCOLOR(220, 220, 220);
        }
    }
    
    return RGBCOLOR(137, 201, 151);
}

- (UIColor *)formView:(KWFormView *)formView contentColorOfColumn:(NSInteger)column inRow:(NSInteger)row
{
    if (row == 0) {
        return [UIColor blackColor];
    }
    
    return [UIColor whiteColor];
}

- (UIColor *)formViewBorderColor:(KWFormView *)formView
{
    return [UIColor whiteColor];
}

- (CGFloat)formView:(KWFormView *)formView widthForColumn:(NSInteger)column
{
    return 80.f;
}

- (CGFloat)formView:(KWFormView *)formView heightForRow:(NSInteger)row
{
    return 50.f;
}

- (BOOL)formView:(KWFormView *)formView addActionForColumn:(NSInteger)column inRow:(NSInteger)row
{
    if (column == 0 || row == 0) {
        return NO;
    }
    
    NSString *time = _timeList[row-1];
    NSMutableDictionary *dic = [_statueList[time][column-1] mutableCopy];
    if ([[dic[@"status"] stringValue] isEqualToString:@"2"] ||
        [[dic[@"status"] stringValue] isEqualToString:@"3"]) {
        return NO;
    }
    
    return YES;
}

- (void)formView:(KWFormView *)formView didSelectColumn:(NSInteger)column inRow:(NSInteger)row {
    
    UIButton *btn = [formView itemAtColumn:column inRow:row];
    btn.selected = !btn.selected;
    
    NSString *time = _timeList[row-1];
    NSMutableDictionary *dic = [_statueList[time][column-1] mutableCopy];
    dic[@"status"] = [NSString stringWithFormat:@"%d", btn.selected];
    
    NSDictionary *unit = @{@"price": dic[@"price"],
                           @"yardNumber": [_yardList[column-1][@"id"] stringValue],
                           @"timesolt": time};
    
    NSInteger findedIndex = [self checkIfExist:unit];
    if (findedIndex < 0) {
        if (yardUnits.count == 4) {
            [Util showHud:@"只能选择4个场地！"];
            btn.selected = NO;
            return;
        }
        
        [yardUnits addObject:unit];
    } else {
        [yardUnits removeObjectAtIndex:findedIndex];
    }
    
    // 确认场地ID
    NSString *yardId = [[yardUnits lastObject] objectForKey:@"yardNumber"];
    _selectedYardId = yardId;
    
    NSInteger tempTotalPrice = 0;
    for (int i=0; i<yardUnits.count; i++) {
        NSDictionary *temp = yardUnits[i];
        tempTotalPrice += [temp[@"price"] integerValue];
    }
    
    self.ibValueLabel.text = [NSString stringWithFormat:@"%ld", (long)tempTotalPrice];
    _totalPrice = self.ibValueLabel.text;
}


@end
